package com.jia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jia.mapper.MyUserMapper;
import com.jia.pojo.Authority;
import com.jia.pojo.MyUser;
import com.jia.pojo.Role;
import com.jia.service.AuthorityService;
import com.jia.service.MyUserService;
import com.jia.service.RoleService;
import com.jia.vo.MyUserList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author 贾宇光
 * @version 1.0
 * @date 2020/9/16 21:59
 */
@Service
public class MyUserServiceImpl extends ServiceImpl<MyUserMapper, MyUser> implements MyUserService, UserDetailsService {

    @Autowired
    MyUserService myUserService;
    @Autowired
    RoleService roleService;
    @Autowired
    AuthorityService authorityService;
    @Autowired
    MyUserMapper myUserMapper;
    @Autowired
    HttpSession session;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //从数据库查询用户信息
        MyUser myUserInfo = myUserService.getOne(new QueryWrapper<MyUser>().eq("username", username));
        if (myUserInfo == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        // 放入session
        session.setAttribute("myUserInfo", myUserInfo);
        //查询权限信息
        Set<SimpleGrantedAuthority> simpleGrantedAuthorities = getAuthorities(myUserInfo.getUid());
        return new User(username, myUserInfo.getPassword(),
                true,
                true,
                true,
                true, simpleGrantedAuthorities);
    }


    /**
     * 权限字符串转化(authorities)
     *
     * @param uid 用户编号
     */
    private Set<SimpleGrantedAuthority> getAuthorities(int uid) {
        List<Authority> list = authorityService.queryAuthorityByUid(uid);
        Set<SimpleGrantedAuthority> simpleGrantedAuthorities = new HashSet<>();
        for (Authority authority : list) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(authority.getName()));
        }
        return simpleGrantedAuthorities;
    }



    @Override
    public List<MyUserList> queryAllByRid(int rid) {
        return myUserMapper.queryAllByRid(rid);
    }


}